import Taro, {Component} from '@tarojs/taro'
import {View,Icon, Input, Image, Text, Textarea, Picker, Button, Label, Checkbox, Swiper, SwiperItem} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import styles from './index.module.scss'
import {AtIcon, AtButton, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui'
import SIGN_TIME_IMG from '@/assets/img/sign_time.png'
import {getTaskListBySquare, submitOrderByTask, confirmOrderByTask, getProtocolByTask, updateOrderByTask, getUserInfo} from '@/api/index'
import { dialog} from '@/util/index';
import { setTaskFun } from '@/actions/task'
import { setUrl } from '@/actions/web'
import { toggleSign, setInfo } from '@/actions/user'
import NoData from "@/components/NoData"
import {PDF_URL} from '@/api/config'

@connect(({user, task}) => ({
  info: user.info,
  isSign: user.isSign,
  merchant:task.merchant
}), dispatch => ({
  setTaskInfo:(data)=>dispatch(setTaskFun(data)),
  setUrl: (data) => dispatch(setUrl(data)),
  setInfo: (data) => dispatch(setInfo(data)),
}))
export default class taskSquare extends Component {

  config = {
    navigationBarTitleText: '任务广场'
  }

  state = {
    pageIndex:1,
    allLoadFlag:false,
    taskList:[],
    merchantName:'',
    id:1,
    isDialog: false,
    dialogContent: '',
    orderNumber: '',
    isContent: false,
    content: '',
    beginTime: undefined,
    endTime: undefined,
    statusList: {
      1: '未接单',
      2: '进行中',
      3: '待验收',
      4: '已驳回',
      5: '已验收',
      6: '已完成',
      7: '已取消',
      8: '已关闭'
    },
    isPoint: false
  }

  constructor() {
    super(...arguments)
    console.log('taskSquare:', this.props.isSign)
  }

  componentWillMount = () => {
    if (!this.props.isSign) {
      Taro.reLaunch({url: '/pages/home/index'})
    }
  }

  componentDidShow = () => {
    const { isSign } = this.props
    if (!isSign) return
    this.selectMer()
    this.getPoint()
  }

  getPoint = async () => {
    try {
      const { merchantName, pageIndex, beginTime, endTime } = this.state
      const { mobile } = this.props.info
      if (!mobile) return
      const { data } = await getTaskListBySquare({merchantName, beginTime, endTime, pageIndex, loginAccount: mobile, taskType: 2 })
      if (data && data.length > 0) {
        this.setState({isPoint: true})
      }
    } catch (e) {
      console.log('getPoint:', e.message)
    }
  }

  getTaskList = async () => {
    const { merchantName, pageIndex, beginTime, endTime, id } = this.state;
    try {
      Taro.showLoading({mask: true, title: '数据加载中...'})
      const { data } = await getTaskListBySquare({merchantName, beginTime, endTime, pageIndex, loginAccount: this.props.info.mobile, taskType: id })
      Taro.hideLoading()
      let arr = data.map(item => {
        return Object.assign({}, item, {checked: true})
      })
      if (data && data.length>0) {
        if (id === 2) { this.setState({isPoint: true}) }
        this.setState(pre => ({taskList: [...pre.taskList, ...arr]}));
        data.length < 10 && this.setState({allLoadFlag:true})
      }else{
        this.setState({allLoadFlag:true, isPoint: false})
      }
    } catch(e) {
      return dialog.toast({title: e.message});
    }
  }
  onReachBottom(){
    if(this.state.allLoadFlag==false){
      this.setState(prevState=>({pageIndex:++prevState.pageIndex}),()=>{
        this.getTaskList();
      })
    }else{
      return dialog.toast({title: '没有更多了', mask: false});
    }
  }

  selectMer(){
    this.setState({taskList:[], allLoadFlag:false, pageIndex:1},()=>{
      this.getTaskList();
    })
  }

  selectTabs(item){
    this.setState({id: item.status, pageIndex: 1, taskList:[], allLoadFlag:false}, () => {
      this.getTaskList()
    });
  }

  confirm(item) {
    if (item.status === 1) {
      if (!item.checked) return
      this.AcceptOrder(item.taskNumber)
    } else if ([2, 4].includes(item.status)) {
      this.setState({orderNumber: item.orderNumber, isDialog: true})
    } else if (item.status === 7) {
      this.AcceptOrder(item.taskNumber)
    } else {
      this.showContent(item)
    }
  }

  showContent(item) {
    this.setState({content: item.taskDeliveryDescription, isContent: true})
  }

  checkBankCard = async () => {
    try {
      const { info, setInfo } = this.props
      const { bankCard, mobile } = info
      if (!bankCard) {
        const { data } = await getUserInfo({loginAccount: mobile})
        if (!data.bankCardNum) {
          Taro.showModal({
            title: '提示',
            content: '您需要完善银行卡信息后才能进行接单',
            confirmText: '去完善',
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                Taro.navigateTo({url: '/pages/user/index'})
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
            showCancel: true
          })
          return false
        } else {
          setInfo({bankCard: data.bankCardNum})
        }
      }
      return true
    } catch (e) {

    }
  }

  async AcceptOrder(taskNumber) {
    try {
      let checkBank = await this.checkBankCard()
      if (!checkBank) return
      Taro.showLoading({mask: true, title: '接单中'})
      const { data } = await submitOrderByTask({loginAccount: this.props.info.mobile, taskNumber})
      Taro.hideLoading()
      dialog.toast({title: '接单成功'})
      this.setState({id: 1}, () => {
        this.selectMer()
      })
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }

  async confirmOrder() {
    try {
      const { orderNumber, dialogContent } = this.state
      const { info } = this.props
      Taro.showLoading({title: '提交订单中...'})
      const { data } = await updateOrderByTask({orderNumber, status: 3, taskDeliveryDescription: dialogContent})
      Taro.hideLoading()
      Taro.showToast({title: '成功', icon: 'success', duration: 2000, mask: false})
      setTimeout(() => {
        this.setState({isDialog: false, dialogContent: ''}, () => {
          this.selectMer()
        })
      }, 2000)
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none', mask: false})
    }
  }

  /**
   * @description 取消任务
   */
  cancelOrder = async (orderNumber) => {
    try {
      Taro.showLoading({mask: true, title: '取消中...'})
      const { data } = await updateOrderByTask({orderNumber, status: 7})
      Taro.hideLoading()
      dialog.toast({title: '取消成功'})
      this.setState({isDialog: false, dialogContent: ''}, () => {
        this.selectMer()
      })
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none', mask: false})
    }
  }

  handlerCheck = (item, index) => {
    this.state.taskList[index].checked = !item.checked
    this.setState({taskList: this.state.taskList})
  }

  getProtocol = async(item) => {
    try {
      Taro.showLoading({title: '正在跳转协议...'})
      const { data } = await getProtocolByTask({id: item.contractId})
      this.checkSystemInfo(data, item.contractTitle)
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none', mask: false})
    }
  }

  checkSystemInfo = (data, title) => {
    let _this = this
    wx.getSystemInfo({
      success (res) {
        if (res.system.indexOf('iOS') != -1) {
          _this.props.setUrl(data)
        } else {
          _this.props.setUrl(PDF_URL + data)
        }
        Taro.hideLoading()
        Taro.navigateTo({url: '/pages/web/index?title=' + title})
      }
    })
  }

  goDetail = (taskNumber) => {
    Taro.navigateTo({url: '/pages/taskDetail/index?id=' + taskNumber})
  }

  render() {
    let { taskList, merchantName, dialogContent, beginTime, endTime, statusList, id, isPoint } = this.state;
    const tabList = [
      { title: '推荐', id: 0, status: 1 },
      { title: '关注', id: 1, status: 2 },
    ];
    return (
      <View className={styles.wrapper}>
        <View className={styles.bannerWrapper}>
          <Swiper
            indicatorColor='#999'
            indicatorActiveColor='#333'
            circular
            indicatorDots
            autoplay
          >
            <SwiperItem>
              <Image src={'../../assets/img/task_square_banner.png'} className={styles.banner}></Image>
            </SwiperItem>
            <SwiperItem>
              <Image src={'http://collect.cocogc.cn/profile/upload/2020/11/12/55afba081690bb34ada95b978419bd14.jpg'} className={styles.banner} onClick={() => Taro.navigateTo({url: '/pages/employComputed/index'})}></Image>
            </SwiperItem>
          </Swiper>
        </View>
        <View className={styles.headWrap}>
          <View className={styles.tabs}>
            {
              tabList.map((item, index)=>{
                return(
                  <View
                    className={id == item.status?`${styles.tab} ${styles.active}`:`${styles.tab}`}
                    onClick={() => this.selectTabs(item)}
                    key={item.id + ''}>
                    {item.title}
                    {(item.status === 2 && isPoint) && <View className={styles.hint}></View>}
                  </View>
                )
              })
            }
          </View>
        </View>
        <View className={styles.waitWrap}>
          {
            (taskList.length>0) ? taskList.map((item, index)=>{
            return(
              <View className={styles.order} key={index + ''} onClick={() => this.goDetail(item.taskNumber)}>
                <View className={styles.nameWrapper}>
                  <View className={styles.name}>{item.taskName}</View>
                  <View className={styles.status}>{statusList[item.status]}</View>
                </View>
                <View className={styles.decRe}>{item.taskDescribe}</View>
                <View className={styles.planEs}>
                  <View className={styles.planName}><Image className={styles.TriangleImg} src={SIGN_TIME_IMG} />任务时长：<Text className={styles.planTime}>{item.missionDuration}</Text></View>
                  <Text className={styles.esName}>预计费用：<Text className={styles.esTime}> {item.acceptanceAmount}</Text></Text>
                </View>
                <View className={styles.decRe}>起止时间：<Text>{item.taskBeginTime} 至 {item.taskEndTime}</Text></View>
                <View className={styles.Merchant}>发布商户：{item.merchantName}</View>
                {item.contractId && <View className={styles.item}>
                  <Label onClick={(e) => {e.stopPropagation();this.handlerCheck(item, index)}}>
                    <Checkbox checked={item.checked}></Checkbox>我已阅读并同意
                  </Label>
                  <Text decode={true} className={styles.theme} onClick={(e) => {e.stopPropagation();this.getProtocol(item)}}>《{item.contractTitle}》</Text>
                </View>}
                {item.status !== 8 && <View className={styles.btnWrapper}>
                  <Button className={item.checked ? styles.confirm: `${styles.confirm} ${styles.disabled}`} onClick={(e) => {e.stopPropagation();this.confirm(item)}}>
                    立即接单
                  </Button>
                </View>}
              </View>
            )
          }) : <NoData></NoData>
        }
        </View>
        <AtModal isOpened={this.state.isDialog} onClose={() => this.setState({isDialog : false})}>
          <AtModalContent>
            {
              this.state.isDialog && <Textarea
                placeholder='填写交付任务内容...'
                style={'width:100%;'}
                placeholderStyle={'color: #cccccc;'}
                maxlength={300}
                value={dialogContent}
                onInput={(e) => this.setState({dialogContent: e.detail.value})}>
              </Textarea>
            }
          </AtModalContent>
          <AtModalAction><Button onClick={() => this.setState({isDialog : false})}>取消</Button><Button onClick={() => this.confirmOrder()}>确定</Button> </AtModalAction>
        </AtModal>
        <AtModal isOpened={this.state.isContent} onClose={() => this.setState({isContent : false})}>
          <AtModalHeader>查看内容</AtModalHeader>
          <AtModalContent>
            {this.state.content}
          </AtModalContent>
          <AtModalAction> <Button onClick={() => this.setState({isContent: false})}>确定</Button></AtModalAction>
        </AtModal>
      </View>
    )
  }

}
